package pers.yanfan.cluster;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.jgroups.JChannel;

import com.gitee.yanfanvip.ClusterBuild;
import com.gitee.yanfanvip.interfaces.Database;
import com.gitee.yanfanvip.util.IPHelp;
import com.gitee.yanfanvip.util.RandomString;

public class Cluster2Node2 {
	static JChannel channel;
	static Database cluster;
	
	public static void main(String[] args) throws Exception {
		cluster = new ClusterBuild("CLUSTER2", 17610, IPHelp.getIPPorts(17600, 17610, 17620))
				.addSite("CLUSTER1", IPHelp.getIPPorts(17500, 17510, 17520))
				.addSite("CLUSTER2", IPHelp.getIPPorts(17600, 17610, 17620))
				.addSite("CLUSTER3", IPHelp.getIPPorts(17700, 17710, 17720))
				.build();
		eventLoop();
	}
	
	static void eventLoop() throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        while(true) {
            try {
                System.out.print("> "); System.out.flush();
                String line = in.readLine().toLowerCase();
                if(line.startsWith("quit") || line.startsWith("exit")) { break; }
                String[] command = line.split(" ");
                switch (command[0]) {
					case "get":
						if(command.length < 3){ throw new RuntimeException("bad command"); }
						byte[] bs = cluster.get(command[1], command[2]);
						if(bs != null){
							System.out.println(new String(bs));
						}else{
							System.out.println("[NULL]");
						}
						break;
					case "put":
						if(command.length < 3){ throw new RuntimeException("bad command"); }
						cluster.put(command[1], command[2], RandomString.next(50).getBytes());
						break;
					default:
						break;
				}
            } catch(Exception e) {
            	e.printStackTrace();
            }
        }
        channel.close();
    }
}
